/*
 * @Author: P.Zhao
 * @Company: HT
 * @Date: 2022-06-13 22:35:08
 * @LastEditors: P.Zhao
 * @LastEditTime: 2022-06-16 16:24:33
 * @Description: cesium加载动图方案三：通过apng-js库实现
 * @FilePath: \practicalCesiumDemos\demos\loadApng\loadApng.js
 */

import viewer from '../../source/core/viewerInstance.js'

let point = [113.94, 23.5]

// 加载apng
loadApng()

// 定位
flyTo()

/**
 * 加载apng
 */
async function loadApng() {
  let url = '../../assets/images/wind.png'
  let canvas = document.createElement('canvas')
  let ctx = canvas.getContext('2d')
  let blob = await loaderURL(url)
  let arrayBuffer = await blobToArrayBuffer(blob)
  let apng = apngjs.parseAPNG(arrayBuffer)
  let player = await apng.getPlayer(ctx)
  player.play()

  let entity = viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(point[0], point[1]),
    billboard: {
      scale: 2
    }
  })

  entity.billboard.image = new Cesium.CallbackProperty(() => {
    return player.currentFrame.imageElement
  }, false)
}

/**
 * 加载图片资源，得到blob类型的值
 * @param {String} url
 * @returns
 */
async function loaderURL(url) {
  function createXmlHttpRequest() {
    if (window.ActiveXObject) {
      return new ActiveXObject('Microsoft.XMLHTTP')
    } else if (window.XMLHttpRequest) {
      return new XMLHttpRequest()
    }
  }
  return new Promise((resolve) => {
    let xhr = createXmlHttpRequest()
    xhr.open('get', url, true)
    xhr.responseType = 'blob'
    xhr.onload = function (res) {
      if (this.status == 200) {
        var blob = this.response
        resolve(blob)
      }
    }
    xhr.send()
  })
}

/**
 * 将blob转换成buffer
 * @param {Blob} blob
 * @returns
 */
async function blobToArrayBuffer(blob) {
  return new Promise((resolve) => {
    // Blob 转 ArrayBuffer
    let reader = new FileReader()
    reader.readAsArrayBuffer(blob)
    reader.onload = function () {
      resolve(reader.result)
    }
  })
}

/**
 * 定位
 */
function flyTo() {
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(point[0], point[1], 1000000),
    duration: 4
  })
}
